package ludichat.cobbreeding

import com.cobblemon.mod.common.api.permission.CobblemonPermission
import com.cobblemon.mod.common.api.permission.PermissionLevel
import com.cobblemon.mod.common.api.pokemon.PokemonSpecies
import com.cobblemon.mod.common.api.text.red
import com.cobblemon.mod.common.command.argument.PokemonPropertiesArgumentType
import com.cobblemon.mod.common.util.commandLang
import com.cobblemon.mod.common.util.permission
import com.cobblemon.mod.common.util.player
import com.mojang.brigadier.Command
import com.mojang.brigadier.CommandDispatcher
import com.mojang.brigadier.context.CommandContext
import net.minecraft.commands.CommandBuildContext
import net.minecraft.commands.CommandSourceStack
import net.minecraft.commands.Commands
import net.minecraft.commands.Commands.argument
import net.minecraft.commands.Commands.literal
import net.minecraft.commands.arguments.EntityArgument
import net.minecraft.server.level.ServerPlayer
import net.minecraft.world.item.ItemStack

object CobbreedingCommands {
    fun register(dispatcher: CommandDispatcher<CommandSourceStack>, registry: CommandBuildContext, selection: Commands.CommandSelection) {
        GivePokemonEgg.register(dispatcher)
    }
}

object GivePokemonEgg {
    fun register(dispatcher: CommandDispatcher<CommandSourceStack>)
    {
        val command = dispatcher.register(literal("givepokemonegg")
                .permission(CobblemonPermission("command.givepokemonegg", PermissionLevel.CHEAT_COMMANDS_AND_COMMAND_BLOCKS))
                .then(argument("player", EntityArgument.player())
                .then(argument("properties", PokemonPropertiesArgumentType.properties())
                        .executes { execute(it, it.player()) })))
    }

    private fun execute(context: CommandContext<CommandSourceStack>, player: ServerPlayer): Int {
        try {
            val pokemonProperties = PokemonPropertiesArgumentType.getPokemonProperties(context, "properties")
            if (pokemonProperties.species == null) {
                player.sendSystemMessage(commandLang("givepokemon.nospecies").red())
                return Command.SINGLE_SUCCESS
            }

            val itemStack = EggUtilities.getEggFromPokemonProperties(pokemonProperties)
            if (itemStack != null)
            {
                player.addItem(itemStack)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return Command.SINGLE_SUCCESS
    }
}